import random
import string
def generate_password(length=8):
characters = string.ascii_letters + string.digits
return ''.join(random.choice(characters) for _ in range(length))
print("你的隨機密碼:", generate_password(12))
說明:
產生由「字母 + 數字」組成的密碼:
需求:
import random
import string
def generate_password(length=12):
if length < 4:
raise ValueError("密碼長度必須至少為 4 才能包含所有類型字符")
# 至少包含各種類型 1 個
password = [
random.choice(string.ascii_uppercase), # 大寫
random.choice(string.ascii_lowercase), # 小寫
random.choice(string.digits), # 數字
random.choice(string.punctuation) # 符號
]
# 剩餘的隨機填充
all_chars = string.ascii_letters + string.digits + string.punctuation
password += [random.choice(all_chars) for _ in range(length - 4)]
# 打亂順序
random.shuffle(password)
return ''.join(password)
print("你的隨機密碼:", generate_password(12))
說明:
今天的挑戰很有趣!把之前學過的隨機數、字串操作、函式都結合起來,真的做出了一個有用的小工具!
明天要進入第十五天!字串的進階操作!會學到字串的更多方法,例如搜尋、取代、分割、大小寫轉換等,讓文字處理變得更靈活!